import React,{useEffect,useState} from 'react'
import {DeleteOutlined,EditOutlined}from '@ant-design/icons'
import http from '../../api'
import {Space,Tag,Table,Popconfirm,Tree,Modal,Button}from 'antd'
import{arrayToTree}from'../../utils/formatSiderData'

export default function Role() {
  const [currow,setCurrow]=useState({})
  const [roleList,setRoleList]=useState([])//角色列表
  const [menuList,setMenuList]=useState([])//编辑时的树级结构
  const [isModalOpen, setIsModalOpen] = useState(false);//编辑弹窗显示控制
  const [checkedKeys,setCheckedKeys]=useState([])//选中的tree节点


//编辑打开详情
const getUserDetil=(record)=>{
  // console.log(record,'>>>>>>')
  setCurrow(record)
  setIsModalOpen(true)
  setCheckedKeys(currow.rights)
}

  const column=[
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm title="确定要删除么？" okText="确认" cancelText="取消" onConfirm={()=>onConfirmDel(record)}>
          <DeleteOutlined style={{color:'red',marginRight:'10px'}} />
          </Popconfirm>
          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>getUserDetil(record)}/>
        </Space>
      ),
    },
  ]

  useEffect(()=>{
    getTableList()
    getMenu()
  },[])


  const onConfirmDel=(record)=>{
    const id=record.id
    http.delete('/roles/'+id).then(res=>{
      console.log(res);
      getTableList()
    })
  }

  //取消编辑
  const cancelEdit=()=>{
    setCheckedKeys([])
    setIsModalOpen(false)
  }

  //勾选key
  const onCheck=(info)=>{
    setCheckedKeys(info)
  }

  //更新userInfo
  const handleOk=()=>{
    http.patch('/roles/'+currow.id,{
      rights:checkedKeys
    }).then(res=>{
      getTableList()
      setIsModalOpen(false)
    })
  }

  const getMenu=()=>{
    const getRootMenu=http.get('/rights')
    const getChildMenu=http.get('/children')
    Promise.all([getRootMenu,getChildMenu]).then(res=>{
      setMenuList(arrayToTree(res[0].data,res[1].data))
    })
  }

  const getTableList=()=>{
    http.get('/roles').then(res=>{
      setRoleList(res.data)
    })
  }
  return (
    <div>
     <Table columns={column} dataSource={roleList} pagination={{ pageSize:5 }} rowKey={(item)=>item.id}/>;
     <Modal title="权限分配" open={isModalOpen} onOk={handleOk} onCancel={cancelEdit}>
     {
      isModalOpen&&
      <Tree
      checkable
      id='id'
      checkStrictly={true}
      checkedKeys={checkedKeys}
      onCheck={onCheck}
      treeData={menuList}
    />
     }
      </Modal>
    </div>
  )
}
